<template>
  <div v-loading="loading" class="package-form-main">
    <el-form
      ref="form"
      :rules="rules"
      label-position="right"
      :model="form"
      size="small "
      label-width="120px"
      class="package-form-container"
    >
      <!--服务商名称-->
      <el-form-item v-if="mode==='add'" label="权限组类型：" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio v-if="!$store.getters.userBanBtnList.includes('SP_RADIO_BOX_SP_PKG')" label="sp">服务商权限组</el-radio>
          <el-radio v-if="!$store.getters.userBanBtnList.includes('SP_RADIO_BOX_MCH_PKG')" label="mch">商户权限组</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-else label="权限组类型：" prop="type">
        {{ form.type === 'sp' ? '服务商权限组' : '商户权限组' }}
      </el-form-item>
      <el-form-item label="权限组名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="说明：" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          maxlength="100"
          show-word-limit
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item v-if="form.type==='sp'" label="服务商功能：" prop="spFeatures">
        <el-checkbox-group v-model="form.spFeatures" :disabled="form.allFeatures">
          <el-checkbox v-for="feature in baseSpFeatures" :key="feature.id" :label="feature.id">{{ feature.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="商户功能：" prop="bizFeatures">
        <el-checkbox-group v-model="form.bizFeatures" :disabled="form.allFeatures">
          <el-checkbox v-for="feature in baseBizFeatures" :key="feature.id" :label="feature.id">{{ feature.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="form.allFeatures" @change="handleAllFeaturesChange">全部功能</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="submitForm">提交{{ mode === 'add' ? '添加' : '更新' }}</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { spPackageFeatures, addSpPackage, updateSpPackage, spPackageDetail } from '@/api/sp/package'
// import { mchPackageFeatures, addMchPackage, updateMchPackage, mchPackageDetail } from '@/api/mch/package'
import { addMchPackage, updateMchPackage, mchPackageDetail } from '@/api/mch/package'

export default {
  props: {
    mode: {
      type: String,
      require: true,
      default: 'add'
    },
    packageType: {
      type: String,
      require: true,
      default: 'sp'
    },
    packageId: {
      type: Number,
      require: false,
      default: null
    }
  },
  data() {
    return {
      // 配置
      rules: {
        type: [
          {
            required: true,
            message: '请选择权限组类型',
            trigger: ['blur', 'change']
          }
        ],
        name: [
          {
            required: true,
            message: '请输入权限组名称',
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            required: true,
            message: '请输入说明',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 状态
      loading: false,
      isShowMoreConfig: false,
      // 数据
      packageList: [],
      baseBizFeatures: [],
      baseSpFeatures: [],
      oldBizFeatures: [],
      oldSpFeatures: [],
      form: {
        type: 'sp',
        allFeatures: false,
        bizFeatures: [],
        description: null,
        name: null,
        spFeatures: []
      }
    }
  },
  computed: {},
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.fetchData()
    this.getSpPackageFeatures()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 获取数据
    fetchData() {
      if (this.mode === 'edit' && this.packageId) {
        this.getDetail()
      } else {
        this.form.type = this.packageType
      }
    },

    // 获取详情
    getDetail() {
      this.packageType === 'sp' ? this.getSpDetail() : this.getMchDetail()
    },

    // 获取mch详情
    getMchDetail() {
      this.loading = true
      mchPackageDetail({ params: { bizPackageId: this.packageId } }).then(res => {
        res.data.bizFeatures = res.data.features ? res.data.features.split(',').map(Number) : []
        res.data.type = 'mch'
        this.form = res.data
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取sp详情
    getSpDetail() {
      this.loading = true
      spPackageDetail({ params: { spPackageId: this.packageId } }).then(res => {
        res.data.type = 'sp'
        this.form = res.data
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取权限
    getSpPackageFeatures() {
      new Promise((resolve, reject) => {
        // const apiFun = this.packageType === 'mch' ? mchPackageFeatures : spPackageFeatures
        this.loading = true
        spPackageFeatures().then(res => {
          this.baseBizFeatures = res.data.baseBizFeatures
          this.baseSpFeatures = res.data.baseSpFeatures
          this.oldBizFeatures = this.parseFeatures(res.data.bizFeatures)
          this.oldSpFeatures = this.parseFeatures(res.data.spFeatures)
          // const bizFeatures = this.oldBizFeatures = this.parseFeatures(res.data.bizFeatures)
          // const spFeatures = this.oldSpFeatures = this.parseFeatures(res.data.spFeatures)
          // if (res.data.allFeatures) {
          //   bizFeatures = this.baseBizFeatures.map(item => {
          //     return item.id
          //   })
          //   spFeatures = this.baseSpFeatures.map(item => {
          //     return item.id
          //   })
          // }
          resolve()
        }).finally(() => {
          this.loading = false
          resolve()
        })
      })
    },

    /**
     * 按钮组
     */
    // 保存
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.allFeatures) {
            params.bizFeatures = []
            params.spFeatures = []
          }
          if (this.mode === 'edit' && params.type === 'mch' || this.mode === 'add' && params.type === 'mch') {
            params.features = params.bizFeatures.join(',')
          }
          let apiFun = null
          if (this.mode === 'add') {
            apiFun = params.type === 'sp' ? addSpPackage : addMchPackage
          } else {
            apiFun = params.type === 'sp' ? updateSpPackage : updateMchPackage
          }
          this.loading = true
          apiFun({ data: params }).then(res => {
            this.$notify({
              title: '成功',
              message: this.mode === 'add' ? '新增成功' : '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            if (this.mode === 'add') this.$refs.form.resetFields()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    // 新增
    add() {

    },

    /**
     * 状态组
     */
    // 全部功能
    handleAllFeaturesChange(val) {
      if (val) {
        this.oldBizFeatures = this.form.bizFeatures
        this.oldSpFeatures = this.form.spFeatures
        const bizFeatures = this.baseBizFeatures.map(item => {
          return item.id
        })
        const spFeatures = this.baseSpFeatures.map(item => {
          return item.id
        })
        this.$set(this.form, 'bizFeatures', bizFeatures)
        this.$set(this.form, 'spFeatures', spFeatures)
      } else {
        this.$set(this.form, 'bizFeatures', this.oldBizFeatures)
        this.$set(this.form, 'spFeatures', this.oldSpFeatures)
      }
    },
    /**
     * 方法组
     */
    //  格式化
    parseFeatures(featureStr) {
      if (!featureStr) {
        return []
      }
      const features = featureStr.split(',')
      return features.map(item => {
        return Number(item)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.package-form-main {

  .el-input, .el-textarea, .el-select {
    width: 500px;
  }

  .package-form-container {
    max-width: 1000px;
  }
}

</style>
